<?php
/**
 * Created by PhpStorm.
 * User: cx
 * Date: 2019-01-09
 * Time: 13:22
 */

namespace services\api;

use Firebase\JWT\JWT;
use yii\base\ErrorException;

class JwtService extends JWT
{
    /**
     * 加密方式
     */
    const JWT_ALGORITHM_METHOD = 'HS256';

    /**
     * 加密secrect
     */
    const JWT_KEY = 'FJKp1oeKME06ksd82';

    /**
     * @param $token
     */
    private static $info = [];

    /**
     * 解析token获取info数据
     * @param $token
     * @return null
     */
    public static function getJwtInfo($token, $type=1)
    {
        if ($type == 2 && !$token) {
            return false;
        }

        if (!empty(self::$info)) {
            return self::$info;
        }

        $jwtKey = self::JWT_KEY;

        try {
            $decodeArr = self::decode($token, $jwtKey, [self::JWT_ALGORITHM_METHOD]);

        } catch (ErrorException $e) {
            return $e->getMessage();
        }

        self::$info = $decodeArr;
        return $decodeArr;
    }

    /**
     * 更新token
     * @param $token
     * @return array|string
     */
    public static function updateJwt($token)
    {
        if (!empty(self::$info)) {
            return self::$info;
        }
        $jwtKey = self::JWT_KEY;

        try {
            $decodeArr = self::decode($token, $jwtKey, [self::JWT_ALGORITHM_METHOD]);
            $tokenInfo = [
                'info' => $decodeArr->info
            ];
            return self::encode($tokenInfo, $jwtKey, self::JWT_ALGORITHM_METHOD);

        } catch (ErrorException $e) {
            return $e->getMessage();
        }

    }

    /**
     * 生成jwt
     * @param $info
     * @return string
     */
    public static function createJwt($info)
    {
        /*$info['iat'] = time();
        $info['exp'] = time() + 86400;*/
        $jwtKey = self::JWT_KEY;
        return self::encode($info, $jwtKey, self::JWT_ALGORITHM_METHOD);
    }

}

